package com.chuangjiangx.member.basic.ddd.application;

import com.chuangjiangx.member.basic.ddd.application.command.CreateMemberAppletQRCodeCommand;
import com.chuangjiangx.member.basic.ddd.application.exception.GetWxAppletQRCodeImageException;
import com.chuangjiangx.member.basic.ddd.application.exception.WxTokenNotFindException;
import com.chuangjiangx.member.basic.ddd.application.result.MemberAppletQRCodeResult;
import com.chuangjiangx.member.basic.ddd.domain.model.WxAccessToken;
import com.chuangjiangx.member.basic.ddd.domain.model.WxAppletToken;
import com.chuangjiangx.member.basic.ddd.domain.model.WxAppletTokenRepository;
import com.chuangjiangx.member.basic.ddd.domain.model.MerchantId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import weixin.popular.api.TokenAPI;
import weixin.popular.api.WxaAPI;
import weixin.popular.bean.token.Token;
import weixin.popular.bean.wxa.Getwxacode;
import weixin.popular.bean.wxa.LineColor;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 会员小程序业务操作类
 *
 * @author 马文韬
 * @version 1.0
 * @date: 2018/9/14
 */
@Service
public class MemberAppletApplication {

    private static final Logger logger = LoggerFactory.getLogger(MemberAppletApplication.class);

    private final String WX_APPLET_PATH = "pages/home/index?merchantId=";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private WxAppletTokenRepository wxAppletTokenRepository;

    public MemberAppletQRCodeResult createQRCode(CreateMemberAppletQRCodeCommand command)
        throws WxTokenNotFindException, GetWxAppletQRCodeImageException {
        // 获取请求商户的微信小程序相关Token信息：app_id，app_secret
        WxAppletToken wxAppletToken = this.wxAppletTokenRepository
                .fromMerchantIdAndProductId(new MerchantId(command.getMerchantId()), command.getProductId());
        if (wxAppletToken == null) {
            throw new WxTokenNotFindException();
        } else {
            // 从Redis中获取缓存的ACCESS_TOKEN
            // TODO : ACCESS_TOKEN 创建时间的获取
            String redisKey = "accesstoken" + command.getStoreId();
            String cachedAccessToken = this.redisTemplate.opsForValue().get(redisKey);
            Long cachedAccessTokenExpireIn = this.redisTemplate.getExpire(redisKey, TimeUnit.SECONDS);
            WxAccessToken accessToken = new WxAccessToken(
                    wxAppletToken.getAuthorizerAppid(), wxAppletToken.getAuthorizerSecret(),
                    cachedAccessToken, cachedAccessTokenExpireIn);

            // 判断ACCESS_TOKEN的有效性，如果失效，需要重新获取
            if (!accessToken.available()) {
                Token responseToken = TokenAPI.token(accessToken.getAppId(), accessToken.getAppSecret());

                if(responseToken == null || responseToken.getAccess_token() == null) {
                    throw new WxTokenNotFindException();
                }
                accessToken = new WxAccessToken(wxAppletToken.getAuthorizerAppid(), wxAppletToken.getAuthorizerSecret(),
                        responseToken.getAccess_token(), Long.valueOf(responseToken.getExpires_in()));
            }

            // 获取二维码图片
            Getwxacode condition = new Getwxacode(
                    WX_APPLET_PATH + command.getMerchantId(),
                    420, false,
                    new LineColor("0", "0", "0"));
            BufferedImage image = WxaAPI.getwxacode(accessToken.value(), condition);

            if(image == null) {
                throw new GetWxAppletQRCodeImageException();
            }

            // 生成结果对象
            MemberAppletQRCodeResult result = new MemberAppletQRCodeResult(image);

            return result;
        }
    }
}
